package servlet;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import config.AlipayConfig;
import model.Orders;
import model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import service.OrdersService;
import service.impl.OrderServiceImpl;
import utils.RandomUUID;
import vo.OrderVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description:
 * @Author one world
 * @Date 2020/9/21 0021 23:26
 */
@WebServlet("/alipay")
public class PayServlet extends HttpServlet{
    private static final Logger logger = LoggerFactory.getLogger(PayServlet.class);
    OrdersService service = new OrderServiceImpl();
    public void toPay(HttpServletRequest request, HttpServletResponse response){
        String idStr = request.getParameter("order_id");
        if(idStr==null||idStr.equals("")){
            return;
        }
        int id = Integer.parseInt(idStr);
        OrderVo orderVo = service.findOrderVoById(id);
        if(orderVo==null){
            return;
        }
        String subject = orderVo.getGoods_name();//商品名称
        String out_order_no = orderVo.getOrder_no();//商户订单编号
        String total_amount=orderVo.getTotal_amount();//金额
        String body=orderVo.getDescription();
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id,AlipayConfig.merchant_private_key,"json",AlipayConfig.charset,AlipayConfig.alipay_public_key,AlipayConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        try{
            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_order_no +"\","
                    + "\"total_amount\":\""+ total_amount +"\","
                    + "\"subject\":\""+ subject +"\","
                    + "\"body\":\""+ body +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            String result;
            result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset="+AlipayConfig.charset);
            response.getWriter().write(result);
            response.getWriter().close();
        }catch (Exception e){
          logger.error("PayServlet支付异常",e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String methodName = req.getParameter("method");
        if(methodName!=null&&!methodName.equals("")){
            if(methodName.equals("toPay")){
                toPay(req,resp);
                //alipay的反馈参数中已经带了一个键值对为method:alipay.trade.page.pay.return的
            }else if(methodName.equals("alipay.trade.page.pay.return")){
                try {
                    payResult(req,resp);
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
            }else if(methodName.equals("pay")){
                toPay(req,resp);
            }else if(methodName.equals("refund")){
                try {
                    refund(req,resp);
                } catch (AlipayApiException e) {
                    logger.error("refund方法退款异常", e);
                }
            }
        }else{
            return;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    public void payResult(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
           if(confirmPayResult(request)){
               Orders order = service.findOrderByOrderNo(out_trade_no);
               order.setTrade_no(trade_no);
               order.setState(1);
               order.setPayment(1);
               service.update(order);
               response.sendRedirect("/xiaomi/order.html");
           }
        }else {
            logger.info("支付宝支付反馈结果验签失败");
        }
    }
    public boolean confirmPayResult(HttpServletRequest request){
        boolean payResult = false;
        try {
//获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //请二选一设置

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"trade_no\":\"" + trade_no + "\"}");

            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            if(result.contains("\"code\":\"10000\",\"msg\":\"Success\"")){
                payResult = true;
                User user = (User) request.getSession().getAttribute("user");
                logger.info("用户："+user.getName()+" 支付成功 支付宝交易号为："+trade_no);
            }
        }catch (UnsupportedEncodingException e){
            logger.error("不支持的编码格式",e);
        }catch (AlipayApiException e){
            logger.error("阿里支付接口异常",e);
        }
       return payResult;
    }

    public void refund(HttpServletRequest request,HttpServletResponse response) throws IOException, AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        String order_no  = request.getParameter("order_no");
        Orders order = service.findOrderByOrderNo(order_no);

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = order_no;
        //支付宝交易号
        String trade_no = order.getTrade_no();
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = order.getReal_price().multiply(new BigDecimal(order.getNumber())).toString();
        //退款的原因说明
            String refund_reason = "退货退款";
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = RandomUUID.getUUID();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        PrintWriter out = response.getWriter();
        if(result!=null&&result.contains("\"code\":\"10000\"")&&service.updateOrderState(order_no,3)){
            out.write(JSON.toJSONString("SUCCESS"));
        }else{
            out.write(JSON.toJSONString("退款失败！"));
        }
        out.close();
    }
}
